package com.plusjun.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plusjun.common.constant.OrderConstant;
import com.plusjun.common.exception.NoStockException;
import com.plusjun.common.to.OrderTO;
import com.plusjun.common.to.SkuHasStockVO;
import com.plusjun.common.to.mq.SeckillOrderTO;
import com.plusjun.common.utils.PageUtils;
import com.plusjun.common.utils.Query;
import com.plusjun.common.utils.R;
import com.plusjun.common.vo.MemberRespVO;
import com.plusjun.gulimall.order.dao.OrderDao;
import com.plusjun.gulimall.order.entity.OrderEntity;
import com.plusjun.gulimall.order.entity.OrderItemEntity;
import com.plusjun.gulimall.order.entity.PaymentInfoEntity;
import com.plusjun.gulimall.order.enume.OrderStatusEnum;
import com.plusjun.gulimall.order.feign.CartFeignService;
import com.plusjun.gulimall.order.feign.MemberFeignService;
import com.plusjun.gulimall.order.feign.ProductFeignService;
import com.plusjun.gulimall.order.feign.WareFeignService;
import com.plusjun.gulimall.order.interceptor.LoginUserInterceptor;
import com.plusjun.gulimall.order.service.OrderItemService;
import com.plusjun.gulimall.order.service.OrderService;
import com.plusjun.gulimall.order.service.PaymentInfoService;
import com.plusjun.gulimall.order.to.OrderCreateTO;
import com.plusjun.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    public static ThreadLocal<OrderSubmitVO> confirmVOThreadLocal = new ThreadLocal<>();
    @Resource
    OrderItemService orderItemService;
    @Resource
    PaymentInfoService paymentInfoService;
    @Resource
    private MemberFeignService memberFeignService;
    @Resource
    private ThreadPoolExecutor poolExecutor;
    @Resource
    private CartFeignService cartFeignService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private ProductFeignService productFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        OrderConfirmVO confirmVO = new OrderConfirmVO();
        CompletableFuture<Void> addressFutureTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 1、远程查询所有的收货地址
            List<MemberAddressVO> address = memberFeignService.getAddress(memberRespVO.getId());
            confirmVO.setAddresses(address);
        }, poolExecutor);

        CompletableFuture<Void> cartItemfutureTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 2、远程购物车，获取所有购物项
            R r = cartFeignService.getCurrentUserCartItems();
            List<OrderItemVO> currentUserCartItems = (List<OrderItemVO>) r.getData("userCartItems", new TypeReference<List<OrderItemVO>>() {
            });
            confirmVO.setItems(currentUserCartItems);
        }, poolExecutor).thenRunAsync(() -> {
            List<Long> skuIds = confirmVO.getItems().stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVO> data = (List<SkuHasStockVO>) r.getData("data", new TypeReference<List<SkuHasStockVO>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock));
                confirmVO.setStocks(map);
            }
        }, poolExecutor);


        // 3、查询用户积分
        Integer integration = memberRespVO.getIntegration();
        confirmVO.setIntegration(integration);

        //4、自动计算其他数据
        // 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVO.getId(), token, 30, TimeUnit.MINUTES);
        confirmVO.setOrderToken(token);
        CompletableFuture.allOf(addressFutureTask, cartItemfutureTask).get();
        return confirmVO;
    }

    //@GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVO submitOrder(OrderSubmitVO orderSubmitVO) {
        confirmVOThreadLocal.set(orderSubmitVO);
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        SubmitOrderResponseVO respVO = new SubmitOrderResponseVO();
        respVO.setCode(0);
        // 验证令牌:从redis中获取、对比、删除，原子性操作
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVO.getOrderToken();
        // 原子验证令牌和删除令牌
        Long res = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVO.getId()),
                orderToken);

        if (res == 0L) {
            // 验证令牌不通过
            respVO.setCode(1);
        } else {
            // 验证令牌通过
            // 创建订单、订单项等信息

            OrderCreateTO orderTO = createOrderTO();
            // 2、验价
            BigDecimal payAmount = orderTO.getOrderEntity().getPayAmount();
            BigDecimal payPriceWeb = orderSubmitVO.getPayPrice();
            if (Math.abs(payAmount.subtract(payPriceWeb).doubleValue()) < 0.01) {
                // 金额对比成功
                saveOrder(orderTO);
                respVO.setCode(0);
                // 库存锁定.只要有异常，回滚订单数据
                // 订单号，所有订单项（skuId，skuName，num）
                WareSkuLockVO lockVO = new WareSkuLockVO();
                lockVO.setOrderSn(orderTO.getOrderEntity().getOrderSn());
                List<OrderItemVO> orderItemVOS = orderTO.getOrderItems().stream().map(item -> {
                    OrderItemVO orderItemVO = new OrderItemVO();
                    orderItemVO.setSkuId(item.getSkuId());
                    orderItemVO.setCount(item.getSkuQuantity());
                    orderItemVO.setTitle(item.getSkuName());
                    return orderItemVO;
                }).collect(Collectors.toList());
                lockVO.setLocks(orderItemVOS);
                // 远程锁库存
                R r = wareFeignService.orderLockStock(lockVO);
                if (r.getCode() == 0) {
                    // 锁定成功
                    respVO.setOrderEntity(orderTO.getOrderEntity());
                    // 远程扣减积分
                    // 订单创建成功，发消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderTO.getOrderEntity());
                } else {
                    // 锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                // 金额对比失败
                respVO.setCode(2);
            }
            return respVO;
        }
        return respVO;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        // 关闭订单之前，查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        // 状态是待付款就需要关单
        if (Objects.equals(orderEntity.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())) {
            OrderEntity updateOrderEntity = new OrderEntity();
            updateOrderEntity.setId(entity.getId());
            updateOrderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateOrderEntity);
            OrderTO orderTO = new OrderTO();
            BeanUtils.copyProperties(entity, orderTO);
            // 订单解锁成功，立即发送一个消息给库存释放
            try {
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTO);
            } catch (Exception e) {
                //
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        String amount = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP).toString();
        payVo.setTotal_amount(amount);
        payVo.setOut_trade_no(orderEntity.getOrderSn());
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        if (CollectionUtils.isNotEmpty(itemEntities)) {
            payVo.setSubject(itemEntities.get(0).getSkuName());
            payVo.setBody(itemEntities.get(0).getSkuAttrsVals());
        }
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItems(Map<String, Object> params) {
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVO.getId()).orderByDesc("id")
        );
        page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntities(orderItemEntities);
            return order;
        });
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        boolean save = paymentInfoService.save(infoEntity);
        // 修改订单状态
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            // 支付成功
            String out_trade_no = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(out_trade_no,OrderStatusEnum.PAYED.getCode());
            return "success";
        }
        return "filed";

    }

    @Override
    public void createSeckillOrder(SeckillOrderTO entity) {
        // 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(entity.getOrderSn());
        orderEntity.setMemberId(entity.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal payamount = entity.getSeckillPrice().multiply(new BigDecimal("" + entity.getNum()));
        orderEntity.setPayAmount(payamount);
        this.save(orderEntity);
        // 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(entity.getOrderSn());
        itemEntity.setRealAmount(payamount);
        // TODO 模糊当前SKU信息信息进行设置
        itemEntity.setSkuQuantity(entity.getNum());
        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单数据
     *
     * @param orderTO
     */
    private void saveOrder(OrderCreateTO orderTO) {
        OrderEntity orderEntity = orderTO.getOrderEntity();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = orderTO.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTO createOrderTO() {
        OrderSubmitVO orderSubmitVO = confirmVOThreadLocal.get();

        OrderCreateTO createTO = new OrderCreateTO();
        // 创建订单
        // 1、订单信息
        // 1.1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrderEntity(orderSn);
        System.out.println("*******************" + orderEntity);
        createTO.setOrderEntity(orderEntity);
        // 2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(createTO.getOrderEntity().getOrderSn());
        createTO.setOrderItems(itemEntities);
        // 3.计算价格相关
        computePrice(createTO);


        System.out.println("*********放回createTO");
        return createTO;
    }

    /**
     * 价格
     *
     * @param createTO
     */
    private void computePrice(OrderCreateTO createTO) {
        List<OrderItemEntity> orderItems = createTO.getOrderItems();
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        Integer giftIntegration = 0;
        Integer giftGrowth = 0;
        // 订单总额：每个订单项总额叠加
        for (OrderItemEntity orderItem : orderItems) {
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            total = total.add(orderItem.getRealAmount());
            giftIntegration = giftIntegration + orderItem.getGiftIntegration();
            giftGrowth = giftGrowth + orderItem.getGiftGrowth();
        }
        // 1、订单价格相关
        OrderEntity orderEntity = createTO.getOrderEntity();
        orderEntity.setTotalAmount(total);
        // 设置应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        // 设置积分等信息
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);
    }

    /**
     * 构建所有订单
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrderEntity(String orderSn) {
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVO.getId());
        // 1.2、这是收货地址收货人 和 运费
        Long addrId = confirmVOThreadLocal.get().getAddrId();
        R fare = wareFeignService.getFare(addrId);
        FareVO fareVO = (FareVO) fare.getData("data", new TypeReference<FareVO>() {
        });
        System.out.println(fare);
        int a = 1 + 1;
        MemberAddressVO memberAddressVO = fareVO.getAddress();
        if (memberAddressVO != null) {
            orderEntity.setFreightAmount(fareVO.getFare());
            orderEntity.setReceiverCity(memberAddressVO.getCity());
            orderEntity.setReceiverDetailAddress(memberAddressVO.getDetailAddress());
            orderEntity.setReceiverName(memberAddressVO.getName());
            orderEntity.setReceiverPhone(memberAddressVO.getPhone());
            orderEntity.setReceiverPostCode(memberAddressVO.getPostCode());
            orderEntity.setReceiverProvince(memberAddressVO.getProvince());
            orderEntity.setReceiverRegion(memberAddressVO.getRegion());
        }
        // 订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // 自动确认时间
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setDeleteStatus(0); // 0代表未删除
        return orderEntity;
    }

    /**
     * 构建所有的订单项数据
     *
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        R r = cartFeignService.getCurrentUserCartItems();
        List<OrderItemVO> currentUserCartItems = (List<OrderItemVO>) r.getData("userCartItems", new TypeReference<List<OrderItemVO>>() {
        });
        if (CollectionUtils.isNotEmpty(currentUserCartItems)) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(item -> {
                OrderItemEntity itemEntity = null;
                try {
                    itemEntity = buildOrderItem(item);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一项订单
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO cartItem) throws ExecutionException, InterruptedException {
        OrderItemEntity itemEntity = new OrderItemEntity();
        // 1、订单信息
        // 2、spu信息
        CompletableFuture<Void> spuInfoFutureTask = CompletableFuture.runAsync(() -> {
            Long skuId = cartItem.getSkuId();
            R r = productFeignService.getSpuInfoBySkuId(skuId);
            SpuInfoVO data = (SpuInfoVO) r.getData(new TypeReference<SpuInfoVO>() {
            });
            itemEntity.setSpuId(data.getId());
            itemEntity.setSpuBrand(data.getBrandId().toString());
            itemEntity.setSpuName(data.getSpuName());
            itemEntity.setCategoryId(data.getCatalogId());
        }, poolExecutor);

        // 3、sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrs(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        // 4、优惠信息
        // 5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        // 6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal(0));
        itemEntity.setIntegrationAmount(new BigDecimal(0));
        // 当前订单项的实际金额
        BigDecimal orignPrice = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal realPrice = orignPrice.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realPrice);
        spuInfoFutureTask.get();
        return itemEntity;
    }

}